//
//  Hear_AddSoundViewController.m
//  Hear
//
//  Created by mac on 2018/4/26.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "Hear_AddSoundViewController.h"

#import "MJRefresh.h"

#import "Hear_AddSoundViewCell.h"

#import "Hear_MusicTypeModel.h"

#import "Hear_MusicListModel.h"

#import "Hear_ProgressView.h"

#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>

@interface Hear_AddSoundViewController () <UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>

@property (nonatomic, strong) UITableView *tableview;

/**  选中cell的下标  */
@property (nonatomic, strong) NSIndexPath *selectIndex;

@property (nonatomic, strong) NSMutableDictionary *param;
@property (nonatomic, assign) int page; // 页数

/** 数据数组 */
@property (nonatomic, strong) NSMutableArray *typearr;
@property (nonatomic, strong) NSMutableArray *typeModelArr;
@property (nonatomic, strong) NSMutableArray *dataArr;

/** 将要进行合成的音乐网络地址 */
@property (nonatomic, copy) NSString *musicURL;

/** 合成音频存储位置 */
@property (nonatomic,strong) NSString *filePath;

@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, weak) Hear_ProgressView *progressView;

/** 音乐选择view */
@property (nonatomic, strong) UIScrollView *chooseView;

@end

/** 全局变量 记录是下拉刷新还是上提加载 */
static BOOL isHeader = YES;

/** 全局变量 判断点击的是否是同一个cell */
static BOOL isSameCell = YES;

@implementation Hear_AddSoundViewController

- (NSString *)filePath {
    if (!_filePath) {
        _filePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
        _filePath = [_filePath stringByAppendingPathComponent:@"user"];
        NSFileManager *manage = [NSFileManager defaultManager];
        if ([manage createDirectoryAtPath:_filePath withIntermediateDirectories:YES attributes:nil error:nil]) {
            _filePath = [_filePath stringByAppendingPathComponent:@"testAudio.aac"];
        }
    }
    return _filePath;
}

- (NSMutableDictionary *)param {
    if (!_param) {
        _param = [NSMutableDictionary dictionary];
    }
    return _param;
}

- (NSMutableArray *)typearr {
    if (!_typearr) {
        _typearr = [NSMutableArray array];
    }
    return _typearr;
}

- (NSMutableArray *)typeModelArr {
    if (!_typeModelArr) {
        _typeModelArr = [NSMutableArray array];
    }
    return _typeModelArr;
}

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = NO;
    
    [self requestTypeData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.translucent = YES;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Hear_AddSoundViewController" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self registrNoti];
    
    [self setupUI];
    
    // 请求数据
    [self.param setObject:[NSString stringWithFormat:@"%d", 10] forKey:@"PageSize"];
    [self refreshData];
    [self.tableview.mj_header beginRefreshing];
    
}

- (void)registrNoti {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Hear_AddSoundViewCellPlayAction:) name:@"Hear_AddSoundViewCell" object:nil];
}

- (void)setupUI {
    self.title = @"添加背景音乐";
    
    UIButton *savebtn = [[UIButton alloc]init];
    savebtn.size = CGSizeMake(30, 25);
    [savebtn setTitle:@"保存" forState:UIControlStateNormal];
    savebtn.titleLabel.font = CustomUIFont(14);
    [savebtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [savebtn addTarget:self action:@selector(savebtnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:savebtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 110, ScreenWidth, ScreenHeight - kTopHeight - 110) style:(UITableViewStylePlain)];
    if (@available(iOS 11.0, *)) {
        self.tableview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever; // UIScrollView也适用
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    tableView.backgroundColor = [UIColor whiteColor];
    tableView.showsVerticalScrollIndicator = NO;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.rowHeight = 100 * scaleHeight;
    [tableView registerClass:[Hear_AddSoundViewCell class] forCellReuseIdentifier:@"Hear_AddSoundViewCell"];
    self.tableview = tableView;
    tableView.tableFooterView = [UIView new];
    
    [self.view addSubview:tableView];
    
    
    self.tableview.emptyDataSetDelegate = self;
    self.tableview.emptyDataSetSource = self;
}

- (BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView {
    return NO;
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"暂无数据"];
}

#pragma mark 请求数据
- (void)requestTypeData {
    
    YTKApi *api = [YTKApi apiGetWithUrl:@"SoundInfo/Get_GetSoundBackgoundMusicTypes" para:nil];
    [api getSuccessToken:^() {
        api.foceNoTocken = NO;
        [api setRequestSerializerType:YTKRequestSerializerTypeJSON];
        [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            
            NSDictionary *dict = request.responseJSONObject;
            
            if ([dict[@"CodeStatus"] integerValue] == 20000) {
                
                NSArray *temparr = [NSArray modelArrayWithClass:[Hear_MusicTypeModel class] json:dict[@"BodyContent"]];
                
                [self.typeModelArr addObjectsFromArray:temparr];
                
                for (Hear_MusicTypeModel *model in temparr) {
                    [self.typearr addObject:model.TypeName];
                }
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIScrollView *chooseview = [[UIScrollView alloc] initWithFrame:CGRectZero];
                    UIScrollView *chooseView = [self creatChooseViewWithTitleArr:self.typearr atView:chooseview];
                    self.chooseView = chooseView;
                    [self.view addSubview:chooseView];
                    
                    [chooseview mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.top.leading.trailing.mas_equalTo(self.view);
                        make.height.mas_equalTo(110);
                    }];
                });
                
            }
            
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            
        }];
    }];
}
- (void)refreshData {
    // 添加头部刷新
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        isHeader = YES;
        self.page = 0;
        [self.param setObject:[NSString stringWithFormat:@"%d", self.page] forKey:@"PageIndex"];
        [self requestMusicListDataWithCode:nil];
    }];
    // 添加尾部加载控件(上提加载)
    self.tableview.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"Hear_AddSoundViewController" object:nil];
        
        isHeader = NO;
        self.page += 1;
        [self.param setObject:[NSString stringWithFormat:@"%d", self.page] forKey:@"PageIndex"];
        [self requestMusicListDataWithCode:nil];
    }];
}

- (void)requestMusicListDataWithCode:(NSString *)TypeCode {
    
    if (isHeader == YES) {
        [self.dataArr removeAllObjects];
    }
    
    if (TypeCode.length) {
        [self.dataArr removeAllObjects];
    }
    
    YTKApi *api = [YTKApi apiGetWithUrl:@"SoundInfo/Get_GetSoundBackgoundMusic" para:self.param];
    [api getSuccessToken:^() {
        api.foceNoTocken = NO;
        [api setRequestSerializerType:YTKRequestSerializerTypeJSON];
        [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            
            [MBProgressHUD hideHUDForView:WINDOW animated:YES];
            
            [self.tableview.mj_header endRefreshing];
            [self.tableview.mj_footer endRefreshing];
            
            NSDictionary *dict = request.responseJSONObject;
            
            if ([dict[@"CodeStatus"] integerValue] == 20000) {
                
                if ([dict[@"Message"] isEqualToString:@"暂无数据"]) {
                    [self showMessage:@"暂无数据" atPosition:ShowPosition_Center];
                }
                
                NSArray *temparr = [NSArray modelArrayWithClass:[Hear_MusicListModel class] json:dict[@"BodyContent"]];
                
                [self.dataArr addObjectsFromArray:temparr];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.tableview reloadData];
                });
            }
            
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            [self.tableview.mj_header endRefreshing];
            [self.tableview.mj_footer endRefreshing];
            [MBProgressHUD hideHUDForView:WINDOW animated:YES];
        }];
    }];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    Hear_AddSoundViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Hear_AddSoundViewCell" forIndexPath:indexPath];
    
    // 防止重用
    //    if (indexPath == self.selectIndex) {
    //        if (isSameCell == YES) {
    //            cell.isSelect = NO;
    //        } else {
    //            cell.isSelect = YES;
    //        }
    //    } else {
    //        cell.isSelect = NO;
    //    }
    
    if (indexPath == self.selectIndex) {
        cell.isSelect = YES;
    } else {
        cell.isSelect = NO;
    }
    
    if (self.dataArr.count > indexPath.row) {
        cell.model = self.dataArr[indexPath.row];
    }
    
    return cell;
}

#pragma mark cell点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //    if (self.selectIndex == indexPath) {
    //        Hear_AddSoundViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    //        cell.isPause = YES;
    //    }
    
    Hear_AddSoundViewCell *cellNone = [tableView cellForRowAtIndexPath:_selectIndex];
    cellNone.isSelect = NO;
    
    self.selectIndex = indexPath;
    
    Hear_AddSoundViewCell *cellSelect = [tableView cellForRowAtIndexPath:indexPath];
    
    //    if ([cellNone isEqual:cellSelect]) {
    //        cellNone.isSelect = NO;
    //        cellSelect.isSelect = NO;
    //        isSameCell = YES;
    //    } else {
    //        cellNone.isSelect = NO;
    //        cellSelect.isSelect = YES;
    //        isSameCell = NO;
    //    }
    
    
    cellSelect.isSelect = YES;
    
    [self.tableview reloadData];
    
    // 获取点击的音频的模型
    Hear_MusicListModel *model = self.dataArr[indexPath.row];
    self.musicURL = model.SongLink;
}


#pragma mark 播放按钮点击事件
- (void)Hear_AddSoundViewCellPlayAction:(NSNotification *)sender {
    Hear_AddSoundViewCell *cell = (Hear_AddSoundViewCell *)sender.object;
    
    // 原本已经选中的cell
    Hear_AddSoundViewCell *cellNone = [self.tableview cellForRowAtIndexPath:_selectIndex];
    // 记录选中的下标
    self.selectIndex = [self.tableview indexPathForCell:cell];
    // 再次选中的cell
    Hear_AddSoundViewCell *cellSelect = [self.tableview cellForRowAtIndexPath:self.selectIndex];
    
    //    if ([cellNone isEqual:cellSelect]) {
    //        cellNone.isSelect = NO;
    //        cellSelect.isSelect = NO;
    //        isSameCell = YES;
    //    } else {
    //        cellNone.isSelect = NO;
    //        cellSelect.isSelect = YES;
    //        isSameCell = NO;
    //    }
    
    cellNone.isSelect = NO;
    cellSelect.isSelect = YES;
    
    [self.tableview reloadData];
    
    // 获取点击的音频的模型
    Hear_MusicListModel *model = self.dataArr[self.selectIndex.row];
    self.musicURL = model.SongLink;
    
}

#pragma mark 保存
#pragma mark 音频的合成操作仅限于本地音频,操作之前进行下载之后获取本地路径进行合成
- (void)savebtnAction:(UIButton *)sender {
    if (!self.musicURL.length) {
        [self showMessage:@"请选择背景音乐" atPosition:ShowPosition_Center];
        return;
    }
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    Hear_ProgressView *view = [[Hear_ProgressView alloc] initWithFrame:window.bounds];
    self.progressView = view;
    [window addSubview:view];
    
    [self addTimer];
    
    self.selectIndex = nil;
    [self.tableview reloadData];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        // 下载网络音乐到本地
        [self downloadSongByURL:self.musicURL];
    });
    
}

- (void)addTimer {
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.2f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}

- (void)timerAction {
    _progressView.progress += 0.01;
    
    if (_progressView.progress >= 0.80) {
        [self removeTimer];
    }
}

- (void)removeTimer {
    [_timer invalidate];
    _timer = nil;
}

#pragma mark 下载操作
- (void)downloadSongByURL:(NSString *)musicStr {
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:musicStr]];
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        [self saveData:data];
        
    }];
    
    [dataTask resume];
}

- (void)saveData:(NSData *)data {
    NSString *savePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    
    savePath = [savePath stringByAppendingPathComponent:@"Music"];
    
    NSFileManager *manager = [NSFileManager defaultManager];
    
    [manager createDirectoryAtPath:savePath withIntermediateDirectories:YES attributes:nil error:nil];
    
    NSString *writePath = [savePath stringByAppendingPathComponent:@"music.mp3"];
    
    BOOL isWrite = [data writeToFile:writePath atomically:YES];
    
    if (isWrite) {
        DDLog(@"写入成功");
        [self mergeAudioWithLocalMusicStr:writePath];
    } else {
        DDLog(@"写入失败");
    }
    
}

#pragma mark 音频合成
- (void)mergeAudioWithLocalMusicStr:(NSString *)musicstr {
    
    AVURLAsset *videoAsset = [AVURLAsset assetWithURL:[NSURL fileURLWithPath:self.soundPath]];
    
    AVURLAsset *audioAsset = [AVURLAsset assetWithURL:[NSURL fileURLWithPath:musicstr]];
    
    AVMutableComposition *compostion = [AVMutableComposition composition];
    
    CMTime interval = CMTimeMakeWithSeconds(5, 1);
    
    // 录音
    AVMutableCompositionTrack *video = [compostion addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:0];
    
    AVMutableAudioMixInputParameters *originalAudioParameters = [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:video];
    [originalAudioParameters setVolumeRampFromStartVolume:1.0 toEndVolume:1.0 timeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration)];
    
    [video insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) ofTrack:[videoAsset tracksWithMediaType:AVMediaTypeAudio].firstObject atTime:interval error:nil];
    
    // 背景音
    AVMutableCompositionTrack *audio = [compostion addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:0];
    
    AVMutableAudioMixInputParameters *bgAudioParameters = [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:audio];
    // 录音开始时降低音量
    CMTime videotime = CMTimeMakeWithSeconds(videoAsset.duration.value / videoAsset.duration.timescale, 1);
    [bgAudioParameters setVolumeRampFromStartVolume:0.15 toEndVolume:0.15 timeRange:CMTimeRangeMake(interval, videotime)];
    
    // 录音结束后增大音量
    CMTime begintime = CMTimeMakeWithSeconds(5 + videoAsset.duration.value / videoAsset.duration.timescale, 1);
    [bgAudioParameters setVolumeRampFromStartVolume:0.15 toEndVolume:1.0 timeRange:CMTimeRangeMake(begintime, interval)];
    
    CMTime totalInter = CMTimeMakeWithSeconds(videoAsset.duration.value / videoAsset.duration.timescale + 10, 1);
    [audio insertTimeRange:CMTimeRangeMake(kCMTimeZero, totalInter) ofTrack:[audioAsset tracksWithMediaType:AVMediaTypeAudio].firstObject atTime:kCMTimeZero error:nil];
    
    /** 赋给对应的类 */
    AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix];
    audioMix.inputParameters = @[originalAudioParameters, bgAudioParameters];
    
    AVAssetExportSession *session = [[AVAssetExportSession alloc]initWithAsset:compostion presetName:AVAssetExportPresetAppleM4A];
    
    NSString *outPutFilePath = [[self.filePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Audio.m4a"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:outPutFilePath]) {
        [[NSFileManager defaultManager] removeItemAtPath:outPutFilePath error:nil];
    }
    
    session.audioMix = audioMix;
    session.outputURL = [NSURL fileURLWithPath:outPutFilePath];
    session.outputFileType = @"com.apple.m4a-audio";
    session.shouldOptimizeForNetworkUse = YES;
    
    [session exportAsynchronouslyWithCompletionHandler:^{
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:outPutFilePath]) {
            
            AVURLAsset *audioAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:outPutFilePath] options:nil];
            CMTime audioDuration = audioAsset.duration;
            float audioDurationSeconds = CMTimeGetSeconds(audioDuration);
            
            if (self.localMusicBlock) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.localMusicBlock(audioDurationSeconds, outPutFilePath);
                    [self hideProgressView];
                });
            }
            
        } else {
            NSLog(@"输出错误");
        }
    }];
    
}

- (void)hideProgressView {
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    
    for (id view in [window subviews]) {
        if([view isKindOfClass:[Hear_ProgressView class]]){
            
            Hear_ProgressView *progressview = (Hear_ProgressView *)view;
            
            if (progressview.progress >= 0.80) {
                progressview.progress = 1;
            } else {
                progressview.progress = 1;
                [self removeTimer];
            }
            
            [UIView animateWithDuration:0.3f animations:^{
            
            } completion:^(BOOL finished) {
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [progressview removeFromSuperview];
                    [self.navigationController popViewControllerAnimated:YES];
                });
                
            }];
            
        }
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UIScrollView *)creatChooseViewWithTitleArr:(NSMutableArray *)titleArr atView:(UIScrollView *)scrollView {
    // 间距
    CGFloat wState = 32;
    // 行距
    CGFloat hState = 15;
    
    for (int i = 0; i < titleArr.count; i++) {
        
        UIButton *button = [[UIButton alloc]init];
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        [button setTitle:titleArr[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithHexString:@"#6E6E6E"] forState:UIControlStateNormal];
        [button setBackgroundColor:[UIColor whiteColor]];
        [button addTarget:self action:@selector(viewBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        button.layer.cornerRadius = 16.5;
        button.layer.masksToBounds = YES;
        button.layer.borderColor = [UIColor colorWithHexString:@"#6E6E6E"].CGColor;
        button.layer.borderWidth = 1;
        
        //设置button的frame
        
        NSInteger x;
        if ([UIScreen mainScreen].bounds.size.width > 375) {
            x = 16 * 2.3;
        } else {
            x = 16;
        }
        
        if (i == 0) {
            button.frame = CGRectMake(x, 15, 93, 32.5);
        }else{
            button.frame = CGRectMake(32 + wState, hState, 93, 32.5);
        }
        
        // 最后一个button如果大于屏幕宽度则进行转行
        if(wState + 125 > kFullWidth){
            hState = hState + 32.5 + 15;
            button.frame = CGRectMake(x, hState, 93, 32.5);
        }
        wState = button.frame.size.width + button.frame.origin.x;
        
        [scrollView addSubview:button];
    }
    
    scrollView.contentSize = CGSizeMake(kFullWidth, hState + 47.5);
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.backgroundColor = [UIColor whiteColor];
    return scrollView;
}

- (void)viewBtnClick:(UIButton *)btn {
    for (UIButton *defaultButton in btn.superview.subviews){
        if ([defaultButton isKindOfClass:[UIButton class]]) {
            
            if (defaultButton == btn) {
                
                defaultButton.selected = YES;
                [defaultButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [defaultButton setBackgroundColor:[UIColor colorWithHexString:@"#2EC8FA"]];
                defaultButton.layer.cornerRadius = 16.5;
                defaultButton.layer.masksToBounds = YES;
                defaultButton.layer.borderColor = [UIColor colorWithHexString:@"#2EC8FA"].CGColor;
                defaultButton.layer.borderWidth = 1;
            }else{
                defaultButton.selected = NO;
                [defaultButton setTitleColor:[UIColor colorWithHexString:@"#6E6E6E"] forState:UIControlStateNormal];
                [defaultButton setBackgroundColor:[UIColor whiteColor]];
                defaultButton.layer.cornerRadius = 16.5;
                defaultButton.layer.masksToBounds = YES;
                defaultButton.layer.borderColor = [UIColor colorWithHexString:@"#6E6E6E"].CGColor;
                defaultButton.layer.borderWidth = 1;
            }
            
        }
    }
    
    NSString *choose =  [self returnButtonTitleAtView:self.chooseView titleModelArr:self.typearr];
    
    for (Hear_MusicTypeModel *model in self.typeModelArr) {
        if ([choose isEqualToString:model.TypeName]) {
            [self.param setObject:model.TypeCode forKey:@"TypeCode"];
            [self requestMusicListDataWithCode:model.TypeCode];
        }
    }
}

- (NSString *)returnButtonTitleAtView:(UIView *)view titleModelArr:(NSMutableArray<NSString *> *)titleArr {
    NSString * str;
    for (id objc in view.subviews){
        if ([objc isKindOfClass:[UIButton class]] ) {
            UIButton *sender = (UIButton *)objc;
            if (sender.isSelected == YES) {
                for (NSString *title in titleArr) {
                    if ([sender.titleLabel.text isEqualToString:title]) {
                        str = title;
                    }
                }
            }
        }
    }
    return str;
}

//- (void)changeStr:(NSString *)soundstr {
//
//    NSString *savePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
//
//    savePath = [savePath stringByAppendingPathComponent:@"Hear_LocalMusic"];
//
//    NSFileManager *manager = [NSFileManager defaultManager];
//
//    [manager createDirectoryAtPath:savePath withIntermediateDirectories:YES attributes:nil error:nil];
//
//    NSString *writePath = [savePath stringByAppendingPathComponent:@"music.mp3"];
//
//    BOOL isWrite = [data writeToFile:writePath atomically:YES];
//
//    if (isWrite) {
//        [self convetM4aToWav:[NSURL URLWithString:soundstr] destUrl:[NSURL URLWithString:writePath]];
//    }
//}

//- (void)convetM4aToWav:(NSURL *)originalUrl destUrl:(NSURL *)destUrl {
//    
//    AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:originalUrl options:nil];    //读取原始文件信息
//    
//    NSError *error = nil;
//    
//    AVAssetReader *assetReader = [AVAssetReader assetReaderWithAsset:songAsset error:&error];
//    
//    if(error) {
//        NSLog (@"error: %@", error);
//        return;
//    }
//    
//    AVAssetReaderOutput *assetReaderOutput = [AVAssetReaderAudioMixOutput assetReaderAudioMixOutputWithAudioTracks:songAsset.tracks audioSettings: nil];
//    
//    if (![assetReader canAddOutput:assetReaderOutput]) {
//        
//        NSLog (@"can't add reader output... die!");
//        return;
//    }
//    
//    [assetReader addOutput:assetReaderOutput];
//    
//    AVAssetWriter *assetWriter = [AVAssetWriter assetWriterWithURL:destUrl
//                                                          fileType:AVFileTypeCoreAudioFormat error: &error];
//    
//    if (error) {
//        
//        NSLog (@"error: %@", error);
//        
//        return;
//        
//    }
//    
//    AudioChannelLayout channelLayout;
//    
//    memset(&channelLayout, 0, sizeof(AudioChannelLayout));
//    
//    channelLayout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
//    
//    NSDictionary *outputSettings = [NSDictionary dictionaryWithObjectsAndKeys:
//                                    
//                                    [NSNumber numberWithInt:kAudioFormatLinearPCM], AVFormatIDKey,[NSNumber
//                                                                                                   numberWithFloat:16000.0], AVSampleRateKey, [NSNumber numberWithInt:2], AVNumberOfChannelsKey, [NSData dataWithBytes:&channelLayout length:sizeof(AudioChannelLayout)], AVChannelLayoutKey, [NSNumber numberWithInt:16], AVLinearPCMBitDepthKey,[NSNumber numberWithBool:NO],
//                                    AVLinearPCMIsNonInterleaved,[NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,[NSNumber numberWithBool:NO], AVLinearPCMIsBigEndianKey,nil];
//    
//    AVAssetWriterInput *assetWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeAudio
//                                                                              outputSettings:outputSettings];
//    
//    if ([assetWriter canAddInput:assetWriterInput]) {
//        
//        [assetWriter addInput:assetWriterInput];
//        
//    } else {
//        
//        NSLog (@"can't add asset writer input... die!");
//        
//        return;
//        
//    }
//    
//    assetWriterInput.expectsMediaDataInRealTime = NO;
//    
//    [assetWriter startWriting];
//    
//    [assetReader startReading];
//    
//    AVAssetTrack *soundTrack = [songAsset.tracks objectAtIndex:0];
//    
//    CMTime startTime = CMTimeMake (0, soundTrack.naturalTimeScale);
//    
//    [assetWriter startSessionAtSourceTime:startTime];
//    
//    __block UInt64 convertedByteCount = 0;
//    
//    dispatch_queue_t mediaInputQueue = dispatch_queue_create("mediaInputQueue", NULL);
//    
//    [assetWriterInput requestMediaDataWhenReadyOnQueue:mediaInputQueue usingBlock: ^{
//        
//        while (assetWriterInput.readyForMoreMediaData) {
//            
//            CMSampleBufferRef nextBuffer = [assetReaderOutput copyNextSampleBuffer];
//            
//            if (nextBuffer) {
//                
//                // append buffer
//                
//                [assetWriterInput appendSampleBuffer: nextBuffer];
//                
//                NSLog (@"appended a buffer (%zu bytes)",CMSampleBufferGetTotalSampleSize
//                       (nextBuffer));
//                
//                convertedByteCount += CMSampleBufferGetTotalSampleSize
//                (nextBuffer);
//                
//            } else {
//                
//                [assetWriterInput markAsFinished];
//                
//                [assetWriter finishWritingWithCompletionHandler:^{
//                    
//                }];
//                
//                [assetReader cancelReading];
//                
//                NSDictionary *outputFileAttributes = [[NSFileManager defaultManager]
//                                                      attributesOfItemAtPath:[destUrl path] error:nil];
//                
//                NSLog (@"FlyElephant %lld",[outputFileAttributes fileSize]);
//                
//                break;
//                
//            }
//            
//        }
//        
//    }];
//    
//}


@end
